
package com.unionServer.gateway;

import com.unionServer.models.GatewayMessage;
import com.unionServer.models.QueueElement;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;

@Slf4j
public class FrontendHandler extends ChannelInboundHandlerAdapter {
    final static Logger logger = Logger.getLogger(FrontendHandler.class);

    public FrontendHandler(){
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    }

    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) throws InterruptedException {

        if (msg instanceof GatewayMessage) {
            GatewayMessage gMessage = (GatewayMessage) msg;

            log.info("1.0 从客户端接收报文长度 : " + gMessage.getMessageLength() + ", 报文内容 : " + gMessage.getMessage());
            // edit the message here



            log.info("1.1 处理后报文长度 : " + gMessage.getMessageLength() + ", 报文内容 : " + gMessage.getMessage());
            MessageQueue.getInstance().add(new QueueElement(gMessage, ctx.channel()));

        }

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        closeOnFlush(ctx.channel());
    }

    /**
     * Closes the specified channel after all queued write requests are flushed.
     */
    public static void closeOnFlush(Channel ch) {
        if (ch.isActive()) {
            ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }
    }
}
